var $ = layui.jquery;
function imgMore(button,num,name){
   var uploader = new plupload.Uploader({
      runtimes: 'html5,flash,silverlight,html4',
      browse_button: button,
      // container: document.getElementById('upImgWrap'),
      multi_selection: true, //是否多选
      url: api.upPath,
      flash_swf_url: api.upPath + '/static/src/js/lib/plupload/js/Moxie.swf',
      silverlight_xap_url: api.upPath + '/static/src/js/lib/plupload/js/Moxie.xap',
      max_file_size: '30mb', // 文件上传最大限制。
      unique_names: true, // 上传的文件名是否唯一
      chunk_size: '5mb', // 分片大小
      filters: {
         mime_types: [{
            title: "Image files",
            extensions: "jpeg,jpg,png"
         }, ]
      },
      init: {
         PostInit: function() {
            // document.getElementById('imglist').innerHTML = '';
         },

         FilesAdded: function(up, files) {
            plupload.each(files, function(file) {
               var imgNow = $("#"+ button +"_list" ).find(".img_item");
               if(!imgNow || imgNow.length < num) {
                  var html = '<div id="' + file.id + '" class="item img_item" style="width: 160px;height: 160px;float: left; border:1px solid #afaaab;\n' +
                      '        border-radius: 3px;margin-bottom: 25px;">'
                  html +=   '<div class="info"></div>'
                  html +=        '<div class="inner" style="text-align: center;position: relative">'
                  html +=  '<a href="javascript:void(0)" class="del_upImg">×</a>'
                  html +=            '<img src="" style="max-width:160px;max-height:160px;">'
                  html +=        '</div>'
                  html += '</div>'
                  $("#"+ button +"_list" ).append(html);
                  $("#"+ button +"_list" ).find(".defaul").remove();
                  // uploader.start();
               }
            });
            plupload.each(files, function(file) {
               previewImage(file, function(url) {
                  console.log(url)
                  $("#"+file.id).find("img").attr("src", url);
                  // $("#"+file.id).find(".a").attr("href", url);
               });
            });
         },

         UploadProgress: function(up, file) {
            if(document.getElementById(file.id)){
               document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
            }
         },

         Error: function(up, err) {
            // document.getElementById('console').appendChild(document.createTextNode("\nError #" + err.code + ": " + err.message));
            console.log(err.message);
         },

         OptionChanged: function(up, option_name, new_value, old_value) {

         }
      }
   });


   uploader.bind('FileUploaded', function(uploader, file, responseObject) {
      var msg = JSON.parse(responseObject.response);
      if (msg.errcode == 0) {
         var html = '<input type="hidden" class="img_path" value="'+msg.data.file_path +'" name="'+name+'">'
         $("#"+file.id).append(html);
      }
   });
   uploader.init();


   function previewImage(file, callback) { //file为plupload事件监听函数参数中的file对象,callback为预览图片准备完成的回调函数
      if (!file || !/image\//.test(file.type)) return; //确保文件是图片
      if (file.type == 'image/gif') { //gif使用FileReader进行预览,因为mOxie.Image只支持jpg和png
         var fr = new moxie.image.Image();
         fr.onload = function() {
            callback(fr.result);
            fr.destroy();
            fr = null;
         }
         fr.readAsDataURL(file.getSource());
      } else {
         var preloader = new moxie.image.Image();
         preloader.onload = function() {
            //preloader.downsize(550, 400);//先压缩一下要预览的图片,宽300，高300
            var imgsrc = preloader.type == 'image/jpeg' ? preloader.getAsDataURL('image/jpeg', 80) : preloader.getAsDataURL(); //得到图片src,实质为一个base64编码的数据
            callback && callback(imgsrc); //callback传入的参数为预览图片的url
            preloader.destroy();
            preloader = null;
         };
         preloader.load(file.getSource());
      }

   }
   return uploader;
}

$('body').on('click','.del_upImg',function (){
   $(this).parents('.img_item').remove();
})

function fillInput(index,value) {
    if(index == 5) {
       return
    }
   if(index === 0) {
      var word = value.substring(3);
      if(word) {
         $(".inputNum").eq(index).val(value.substring(0,3))
         $(".inputNum").eq(index + 1).val(word);
         $(".inputNum").eq(index + 1).focus();
         fillInput(index + 1,word)
      }
   }
   if(index === 1 || index === 4) {
      var word = value.substring(1);
      if(word) {
         $(".inputNum").eq(index).val(value.slice(0,1))
         $(".inputNum").eq(index + 1).val(word);
         $(".inputNum").eq(index + 1).focus();
         fillInput(index + 1,word)
      }
      // var word = value.slice(i,i + 1);
   }
   if(index === 2 || index === 3) {
      var word = value.substring(4);
      if(word) {
         $(".inputNum").eq(index).val(value.slice(0,4))
         $(".inputNum").eq(index + 1).val(word);
         $(".inputNum").eq(index + 1).focus();
         fillInput(index + 1,word)
      }
   }
}


$(function (){
   imgMore('boxBtn',5,'upImg');
   $(".inputNum").map(function (i,ele) {
      $(this).on("input", function(ele,i){
         var value = $(this).val();
         var index =  $(".inputNum").index($(this));
         fillInput(index,value)
      })
   });
})
